<html>
  <head>
    <title>Bamboo Checker</title>
    <style type="text/css">
    .example {
      font-size: small;
    }
    input[type="text"], input[type="password"]{
      width: 21em;
    }
    
    th {
      text-align: left;
    }
    </style>
    
    <script type="text/javascript" src="classes.js"></script>
    <script type="text/javascript">
    function extractUrlDetails(serverUrl) {
      var urlParts = serverUrl.split("://");
      if (urlParts.length == 1) {
        var scheme = "http";
        var host = urlParts[0];
      } else {
        var scheme = urlParts[0];
        var host = urlParts.slice(1, urlParts.length).join("://");
      }
      return {scheme: scheme, host: host};
    }
    
    function grabServerFromPage(serverNumber) {
      var urlDetails = extractUrlDetails(document.getElementById("server" + serverNumber).value);
      var scheme = urlDetails.scheme;
      var host = urlDetails.host;
      var username = document.getElementById("username" + serverNumber).value;
      var password = document.getElementById("password" + serverNumber).value;
      return new Server(scheme, host, username, password);
    }
    
    function save() {
      var updateInterval = parseInt(document.getElementById("updateInterval").value);
      if (!isNaN(updateInterval)) {
        localStorage["updateInterval"] = updateInterval;
      }
    
      var servers = [];
      var serverblocks = document.getElementsByClassName("serverblock");
      for (var sb = 0; sb < serverblocks.length; ++sb) {
        var server = grabServerFromPage(sb);
        
        var planCheckBoxes = document.getElementById("server" + sb + "retrievedPlans").getElementsByTagName("input");
        for (var p = 0; p < planCheckBoxes.length; ++p) {
          var planName = planCheckBoxes[p].getAttribute("value");
          //Plan(server, planName, passing, disabled, ignored)
          var plan = new Plan(server, planName, PlanStatus.UNKNOWN, PlanStatus.UNKNOWN, (planCheckBoxes[p].checked ? PlanStatus.NOT_IGNORED : PlanStatus.IGNORED));
          server.addPlan(plan);
        }
        servers.push(server);
      }
      saveServersAndPingBackgroundPage(servers);
      populate();
    }
    
    function populate() {
      if (localStorage["updateInterval"] === undefined) {
        localStorage["updateInterval"] = 5;
      }
      var updateInterval = localStorage["updateInterval"];
      document.getElementById("updateInterval").value = updateInterval;
    
      var servers = localStorage["servers"];
      if (servers === undefined || (servers = JSON.parse(servers)).length == 0) {
        servers = [new Server("", "", "", "")];
        servers[0].addPlan(new Plan(servers[0], ""));
      }
      for (var s in servers) {
        var server = servers[s];
        document.getElementById("server" + s).value = (server.scheme == "") ? "" : server.scheme + "://" + server.host;
        document.getElementById("username" + s).value = server.username;
        document.getElementById("password" + s).value = server.password;
        populateRetrievedPlans(s, false, false);
      }
    }
    
    function populateRetrievedPlans(serverNumber, force, update) {
      getServerDetailsFromLocalStorage();
      
      var retrievedPlansTd = document.getElementById("server" + serverNumber + "retrievedPlans");
      var server = grabServerFromPage(serverNumber);
      if (server.scheme === "" || server.host === "") {
        return;
      }
      retrievedPlansTd.innerHTML = "Please wait, updating...";
      server.listPlans(function(response) {
        if (response.status == 200) {
          retrievedPlansTd.innerHTML = "";
          var table = document.createElement("table");
          table.setAttribute("style", "width: 100%");
          var tr = document.createElement("tr");
          tr.innerHTML = "<th>Plan</th><th>Monitor?</th>";
          table.appendChild(tr);
          
          var parser = new DOMParser();
          var xmlDoc = parser.parseFromString(response.responseText, "text/xml");
          var planElements = xmlDoc.getElementsByTagName("plan");
          var plans = [];
          for (var p = 0; p < planElements.length; ++p) {
            var plan = new Plan(null, planElements[p].getAttribute("key"));
            plans.push(plan);
          }
          var savedServer = servers[serverNumber];
          for (var p = 0; p < plans.length; ++p) {
            var tr = document.createElement("tr");
            var td = document.createElement("td");
            td.innerHTML = plans[p].planName;
            tr.appendChild(td);
            var td = document.createElement("td");

            if (savedServer !== undefined) {
              var checked = false;
              for (var sp = 0; sp < savedServer.plans.length; ++sp) {
                var savedPlan = savedServer.plans[sp];
                if (savedPlan.planName == plans[p].planName && savedPlan.ignored !== PlanStatus.IGNORED) {
                  checked = true;
                  break;
                }
              }
            }
            
            td.innerHTML = "<input type='checkbox'" + (checked ? " checked='checked'" : "") + "value='" + plans[p].planName + "' />";
            tr.appendChild(td);
            table.appendChild(tr);
          }
          retrievedPlansTd.appendChild(table);
          document.getElementById("server" + serverNumber + "updateplans").innerHTML = '<a href="#" onclick="populateRetrievedPlans(' + serverNumber + ', true, true)">Update</a>';
        } else {
          var currentText = (retrievedPlansTd.innerHTML + "");
          if (update && (force || currentText.indexOf("populateRetrievedPlans") != -1) || currentText.indexOf("Please wait, updating...") != -1) {
            retrievedPlansTd.innerHTML = "Could not connect to server<br /><a href='#' onclick='populateRetrievedPlans(" + serverNumber + ", false, true)'>Populate</a>";
          }
        }
      });
    }
    </script>
  </head>
  <body onload="populate(); document.getElementById('save').onclick = save;" style="width: 600px;">
    <h2>Bamboo Checker Settings</h2>
    <form id="options" name="options" action="options.html" method="POST">
      <div class="serverblock" id="serverblock0">
        <table>
          <tr><td><label for="updateInterval">Update interval:</label></td><td><input type="text" id="updateInterval" name="updateInterval" /></td><td class="example">(In minutes)</td></tr>
          <tr><td><label for="server0">Server: </label></td><td><input type="text" id="server0" name="server0" /></td><td><span class="example">e.g. http://xserve.openqa.org:8085/path/to/bamboo</span></td></tr>
          <tr><td><label for="username0">Username: </label></td><td><input type="text" id="username0" name="username0" /></td><td></td></tr>
          <tr><td><label for="password0">Password: </label></td><td><input type="password" id="password0" name="password0" /></td><td></td></tr>
          <tr><td style="vertical-align: top;"><label for="server0retrievedplans">Plans: </label></td><td id="server0retrievedPlans"><a href="#" onclick="populateRetrievedPlans(0, false, true)">Populate</a></td><td id="server0updateplans"></td></tr>
          <tr><td><input type="button" value="Save" id="save" /></td></tr>
        </table>
      </div>
    </form>
  </body>
</html>